package mark.tom.fiter;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

import mark.tom.fiter.bean.AggregateBean;
import mark.tom.fiter.bean.ResolvedAggregateBean;

public abstract class DTOConverter<RESULT, SOURCE> extends AbstractDTOConverter<RESULT, SOURCE> {

    @SuppressWarnings("unchecked")
    @NonNull
    @Override
    public AggregateBean convert(@NonNull AggregateBean aggregateBean) {
        if (aggregateBean instanceof ResolvedAggregateBean) {
            Object data = ((ResolvedAggregateBean) aggregateBean).getData();
            if (null != data) {
                if (data instanceof List) {
                    List<SOURCE> mSourceList = (List<SOURCE>) data;
                    List<RESULT> mResultList = new ArrayList<>(mSourceList.size());
                    for (int i = 0; i < mSourceList.size(); i++) {
                        mResultList.add(convert(mSourceList.get(i)));
                    }
                    ((ResolvedAggregateBean) aggregateBean).setData(mResultList);
                } else if (!(data instanceof String)) {
                    RESULT result = convert((SOURCE) data);
                    ((ResolvedAggregateBean) aggregateBean).setData(result);
                }
            }
        }
        return aggregateBean;
    }
}
